let userTodaySort = document.getElementById("userTodaySort")
let userTomorrowSort = document.getElementById("userTomorrowSort")
let userTomorrowSortIcon= document.getElementById("userTomorrowSortIcon")
let userTodaySortIcon = document.getElementById("userTodaySortIcon");
userTodaySort.addEventListener("click",(event)=>{
    if (Cookies.get("userTodaySort")=="OldToNew") {
        Cookies.set("userTodaySort","NewToOld")
        document.location.reload()
    }else  {
        Cookies.set("userTodaySort","OldToNew")
        document.location.reload()
    }


})
userTomorrowSort.addEventListener("click",(event)=>{

    if (Cookies.get("userTomorrowSort")=="OldToNew") {
        Cookies.set("userTomorrowSort","NewToOld")

        document.location.reload()

    }else  {
        Cookies.set("userTomorrowSort","OldToNew")
        document.location.reload()
    }

})

window.addEventListener("load", (event) => {
    if (Cookies.get("userTodaySort")=="OldToNew") {
        userTodaySortIcon.setAttribute("class","glyphicon glyphicon-triangle-top")
    }else  {
        userTodaySortIcon.setAttribute("class","glyphicon glyphicon-triangle-bottom")
    }

    if (Cookies.get("userTomorrowSort")=="OldToNew") {
        userTomorrowSortIcon.setAttribute("class","glyphicon glyphicon-triangle-top")

    }else  {
        userTomorrowSortIcon.setAttribute("class","glyphicon glyphicon-triangle-bottom")
    }
    let todaydate = new Date()
    document.getElementById("todayDateTime").innerText = `Today Tasks:${todaydate.getMonth() + 1}|${todaydate.getDate()}|${todaydate.getFullYear()}`
    let tommorrowDate = new Date(todaydate.getTime() + 86400000)
    document.getElementById("tommorrowDateTime").innerText = `Tomorrow Tasks:${tommorrowDate.getMonth() + 1}|${tommorrowDate.getDate()}|${tommorrowDate.getFullYear()}`


    if (Cookies.get("todayTimeSort")=="OldToNew") {
        url ="/user/selectUserTodayTasksTimeEsc"
    }
    else if (Cookies.get("todayTimeSort")=="NewToOld"){
        url ="/user/selectUserTodayTasksTimeDesc"
    }else {
        url = "/user/selectUserTodayTasks"
    }



    $.post(url, null, (res) => {
        if (res.status == "3001") {
            alert(res.message)
            document.location = "/public/html/home.html"
        } else if (res.data) {


            let today_tasks_table = document.querySelector("#today_tasks_table>tbody");

            for (let resArrayElement of res.data) {
                let tr = document.createElement("tr")
                for (let objKeyAndValue in resArrayElement) {
                    let td = document.createElement("td")
                    if (objKeyAndValue == "due_date") {
                        let timeBigInt = resArrayElement[`${objKeyAndValue}`] * 1000
                        let date = new Date(timeBigInt)
                        let dateMinutes = date.getMinutes().toString();
                        if (dateMinutes.length < 2) {
                            dateMinutes = `0${dateMinutes}`
                        }
                        td.innerText = `${date.getHours()}:${dateMinutes}`
                    } else if (objKeyAndValue == "description") {
                        continue;
                    } else {
                        td.innerText = resArrayElement[`${objKeyAndValue}`]
                    }

                    tr.appendChild(td)

                }
                let tdOpration = document.createElement("td")
                let cancelButton = document.createElement("button")
                cancelButton.setAttribute("type", "button")
                cancelButton.setAttribute("data-taskid", resArrayElement.id)
                cancelButton.innerText = "CANCEL"
                cancelButton.classList.add("button")
                cancelButton.classList.add("btn-warning")
                cancelButton.addEventListener("click", (event) => {
                    let taskid = event.target.getAttribute("data-taskid")
                    $.post("/user/cancelOneTask", {"taskid": taskid}, (res) => {
                        if (res.status == "3001") {
                            alert(res.message)
                            document.location = "/public/html/home.html"
                        } else {
                            alert(res.message)
                            location.reload()

                        }

                    }, "json")
                });
                let submitButton = document.createElement("button")
                submitButton.setAttribute("type", "button")
                submitButton.setAttribute("data-taskid", resArrayElement.id)
                submitButton.setAttribute("data-taskname", resArrayElement.title)
                submitButton.setAttribute("data-description", resArrayElement.description)
                submitButton.setAttribute("data-catagory", resArrayElement.catagory)
                submitButton.setAttribute("data-due-date", resArrayElement.due_date)
                submitButton.setAttribute("data-marks", resArrayElement.marks)
                submitButton.innerText = "EDIT"
                submitButton.classList.add("button")
                submitButton.classList.add("btn-primary")
                submitButton.addEventListener("click", (event) => {
                    let taskid = event.target.getAttribute("data-taskid")
                    let taskname = event.target.getAttribute("data-taskname")
                    let catagory = event.target.getAttribute("data-catagory")
                    let due_date = event.target.getAttribute("data-due-date")
                    let description = event.target.getAttribute("data-description")
                    let marks = event.target.getAttribute("data-marks")

                    Cookies.set('currentTaskID', taskid)
                    Cookies.set('currentTaskName', taskname)
                    Cookies.set('currentTaskcatagory', catagory)
                    Cookies.set('currentTaskDueDate', due_date)
                    Cookies.set('currentTaskMarks', marks)
                    Cookies.set('currentTaskDescription', description)
                    document.location = "./UserTasks.html"

                })
                let emailButton = document.createElement("button")
                emailButton.setAttribute("type", "button")
                emailButton.setAttribute("data-taskid", resArrayElement.id)
                emailButton.setAttribute("data-taskname", resArrayElement.title)
                emailButton.innerText = "EMAIL"
                emailButton.classList.add("button")
                emailButton.classList.add("btn-success")
                emailButton.addEventListener("click", (event) => {
                    let taskid = event.target.getAttribute("data-taskid")
                    let date = new Date();
                    let noticeTime = prompt(`Imput Task: ${taskid}'s Notice Time:`, `${date.getFullYear()} ${date.getMonth() + 1} ${date.getDate() + 1} 00:00:00`)
                    let restSeconds = Math.round(new Date(noticeTime).getTime() / 1000) - Math.round(new Date().getTime() / 1000)

                    let noticeEmailAddress = prompt("Input Notification Email Address", "123@qq.com")


                    if (restSeconds && noticeEmailAddress) {
                        $.post("/user/updateTaskEmailNotificationStatus",
                            {
                                "sendTime": restSeconds,
                                "sendToWho": noticeEmailAddress,
                                "sendWhat": `It's time to finish: ${event.target.getAttribute("data-taskname")}`,
                                "taskid":taskid
                            }, function (res) {
                                alert(`Ok,Email Notification has been setting ,Rest Seconds:${restSeconds}`)
                            }, "json")
                    } else {
                        alert("you have cancel a email notification")
                    }

                })

                tdOpration.appendChild(submitButton)
                tdOpration.appendChild(cancelButton)
                tdOpration.appendChild(emailButton)
                tr.appendChild(tdOpration)

                today_tasks_table.appendChild(tr)
            }
        } else {
            let today_tasks_table = document.querySelector("#today_tasks_table>tbody");
            let tr = document.createElement("tr")
            let td = document.createElement("td")
            td.innerText = "No Today Tasks"
            tr.appendChild(td)
            today_tasks_table.appendChild(tr)

        }

    }, "json")
    let userTomorrowTaskUrl
    if (Cookies.get("userTomorrowSort")=="OldToNew") {
        userTomorrowTaskUrl ="/user/selectUserTomorrowTasksEscTime"
    }
    else if (Cookies.get("userTomorrowSort")=="NewToOld"){
        userTomorrowTaskUrl ="/user/selectUserTomorrowTasksDescTime"
    }else {
        userTomorrowTaskUrl = "/user/selectUserTommorrowTasks"
    }



    $.post(userTomorrowTaskUrl, null, (res) => {


        if (res.data) {

            let tomorrow_tasks_table = document.querySelector("#tomorrow_tasks_table>tbody");

            for (let resArrayElement of res.data) {
                let tr = document.createElement("tr")
                for (let objKeyAndValue in resArrayElement) {
                    let td = document.createElement("td")
                    if (objKeyAndValue == "due_date") {
                        let timeBigInt = resArrayElement[`${objKeyAndValue}`]*1000
                        let date = new Date(timeBigInt)
                        let dateMinutes = date.getMinutes().toString();
                        if (dateMinutes.length < 2) {
                            dateMinutes = `0${dateMinutes}`
                        }
                        td.innerText = `${date.getHours()}:${dateMinutes}`
                    } else {
                        td.innerText = resArrayElement[`${objKeyAndValue}`]
                    }
                    tr.appendChild(td)
                }
                tomorrow_tasks_table.appendChild(tr)
            }
        } else {
            let tomorrow_tasks_table = document.querySelector("#tomorrow_tasks_table>tbody");
            let tr = document.createElement("tr")
            let td = document.createElement("td")
            td.innerText = "No Tomorrow Tasks"
            tr.appendChild(td)
            tomorrow_tasks_table.appendChild(tr)

        }


    })
})


